<template>
  <div class="member-container">
    <div class="header">
      <h2>成员列表</h2>
      <el-tooltip content="创建成员" placement="top">
        <el-button class="create-btn" @click="showCreateDialog = true">
          <img src="@/assets/icon/more-icon.png" alt="创建" class="create-icon"/>
        </el-button>
      </el-tooltip>
    </div>
    
    <!-- 创建用户对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建成员"
      width="500px"
    >
      <el-form :model="newUser" :rules="rules" ref="createFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUser.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="newUser.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="newUser.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="普通用户" value="USER"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreate">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <table class="member-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>身份</th>
          <th>用户名</th>
          <th>昵称</th>
          <th>邮箱</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="member in members" :key="member.id">
          <td>{{ member.id }}</td>
          <td>{{ formatRole(member.role) }}</td>
          <td>{{ member.username }}</td>
          <td>{{ member.nickname }}</td>
          <td>{{ member.email }}</td>
          <td>
            <button class="action-btn">
              <i class="more-icon">⋮</i>
            </button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup lang="ts">
import { User,ListUsersResponse, CreateUserRequest } from "@/types/proto/api/v1/user_service";
import { Role } from "@/types/proto/common/common";
import { ListUsers, CreateUser } from "@/api/user";
import { ref, onMounted, nextTick, computed } from 'vue'
import type { FormInstance } from 'element-plus'
import { useUserStore } from "@/store/user";

const pageSize = 10
const totalMember = ref(0)
const members = ref<User[]>([])
const userStore = useUserStore()

const showCreateDialog = ref(false)
const createFormRef = ref<FormInstance>()

const newUser = ref({
  username: '',
  nickname: '',
  password: '',
  role: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const loadUsers = () => {
  const pageToken = { limit: pageSize, offset: 0 }
  const filter = ""
  ListUsers({ pageSize: pageSize, pageToken, filter: filter }).then((res:ListUsersResponse)=>{
    totalMember.value = res.totalSize
    members.value=[]
    res.users.forEach((user) => {
      members.value.push(user)
    })
  }).catch(error => {
      console.error('Failed to fetch news:', error)
  })
}

const handleCreate = async () => {
  console.log("handle create")
  if (!createFormRef.value) return
  console.log("handle create1")

  await createFormRef.value.validate(async (valid) => {
    console.log("handle create2")

    if (valid) {
      console.log("handle create3")

      try {
        // 这里添加创建用户的 API 调用
        let req = {username:newUser.value.username, 
                  password:newUser.value.password, 
                  nickname:newUser.value.nickname,
                  tenantUrn:userStore.tenantUrn} as CreateUserRequest
        switch (newUser.value.role) {
          case "ADMIN":
            req.role = Role.TENANT_ADMIN
            break;
          case "USER":
            req.role = Role.USER
            break;
          defalut:
             req.role = Role.USER
        }

        const res = await CreateUser(req)
        console.log("create res:", res.urn)
        
        showCreateDialog.value = false
        // 重新加载用户列表
        loadUsers()
        // 重置表单
        newUser.value = {
          username: '',
          nickname: '',
          password: '',
          role: ''
        }
      } catch (error) {
        console.error('Failed to create user:', error)
      }
    }
  })
}

const formatRole = (role: string) => {
  switch (role) {
    case 'USER':
      return '普通用户';
    case 'TENANT_ADMIN':
      return '管理员';
    case 'AI_ASSISTANT':
      return '智能体';
    default:
      return role; // 如果没有匹配的角色，返回原始角色
  }
}

onMounted(() => {
  // 可以在这里加载初始数据
  loadUsers()
})
</script>

<style scoped lang="scss">
.member-container {
  padding: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h2 {
    font-size: 20px;
    font-weight: 500;
  }
}

.create-btn {
  background: transparent;
  border: none;
  padding: 8px;
  
  &:hover {
    background-color: rgba(0, 0, 0, 0.04);
  }

  &:focus {
    background-color: transparent;
  }
}

.create-icon {
  width: 16px;
  height: 16px;
}

.member-table {
  width: 100%;
  border-collapse: collapse;
  
  th, td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #f0f0f0;
  }

  th {
    background: #fafafa;
    font-weight: 500;
    color: #666;
  }
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;

  &:hover {
    background: #f5f5f5;
  }
}

.more-icon {
  font-style: normal;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}
</style>
